{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "00ea4628",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# Generalization in Deep Learning\n",
    "\n",
    "\n",
    "In :numref:`chap_regression` and :numref:`chap_classification`,\n",
    "we tackled regression and classification problems\n",
    "by fitting linear models to training data.\n",
    "In both cases, we provided practical algorithms\n",
    "for finding the parameters that maximized\n",
    "the likelihood of the observed training labels.\n",
    "And then, towards the end of each chapter,\n",
    "we recalled that fitting the training data\n",
    "was only an intermediate goal.\n",
    "Our real quest all along was to discover *general patterns*\n",
    "on the basis of which we can make accurate predictions\n",
    "even on new examples drawn from the same underlying population.\n",
    "Machine learning researchers are *consumers* of optimization algorithms.\n",
    "Sometimes, we must even develop new optimization algorithms.\n",
    "But at the end of the day, optimization is merely a means to an end.\n",
    "At its core, machine learning is a statistical discipline\n",
    "and we wish to optimize training loss only insofar\n",
    "as some statistical principle (known or unknown)\n",
    "leads the resulting models to generalize beyond the training set.\n",
    "\n",
    "\n",
    "On the bright side, it turns out that deep neural networks\n",
    "trained by stochastic gradient descent generalize remarkably well\n",
    "across myriad prediction problems, spanning computer vision;\n",
    "natural language processing; time series data; recommender systems;\n",
    "electronic health records; protein folding;\n",
    "value function approximation in video games\n",
    "and board games; and numerous other domains.\n",
    "On the downside, if you were looking\n",
    "for a straightforward account\n",
    "of either the optimization story\n",
    "(why we can fit them to training data)\n",
    "or the generalization story\n",
    "(why the resulting models generalize to unseen examples),\n",
    "then you might want to pour yourself a drink.\n",
    "While our procedures for optimizing linear models\n",
    "and the statistical properties of the solutions\n",
    "are both described well by a comprehensive body of theory,\n",
    "our understanding of deep learning\n",
    "still resembles the wild west on both fronts.\n",
    "\n",
    "Both the theory and practice of deep learning\n",
    "are rapidly evolving,\n",
    "with theorists adopting new strategies\n",
    "to explain what's going on,\n",
    "even as practitioners continue\n",
    "to innovate at a blistering pace,\n",
    "building arsenals of heuristics for training deep networks\n",
    "and a body of intuitions and folk knowledge\n",
    "that provide guidance for deciding\n",
    "which techniques to apply in which situations.\n",
    "\n",
    "The summary of the present moment is that the theory of deep learning\n",
    "has produced promising lines of attack and scattered fascinating results,\n",
    "but still appears far from a comprehensive account\n",
    "of both (i) why we are able to optimize neural networks\n",
    "and (ii) how models learned by gradient descent\n",
    "manage to generalize so well, even on high-dimensional tasks.\n",
    "However, in practice, (i) is seldom a problem\n",
    "(we can always find parameters that will fit all of our training data)\n",
    "and thus understanding generalization is far the bigger problem.\n",
    "On the other hand, even absent the comfort of a coherent scientific theory,\n",
    "practitioners have developed a large collection of techniques\n",
    "that may help you to produce models that generalize well in practice.\n",
    "While no pithy summary can possibly do justice\n",
    "to the vast topic of generalization in deep learning,\n",
    "and while the overall state of research is far from resolved,\n",
    "we hope, in this section, to present a broad overview\n",
    "of the state of research and practice.\n",
    "\n",
    "\n",
    "## Revisiting Overfitting and Regularization\n",
    "\n",
    "According to the \"no free lunch\" theorem of :citet:`wolpert1995no`,\n",
    "any learning algorithm generalizes better on data with certain distributions, and worse with other distributions.\n",
    "Thus, given a finite training set,\n",
    "a model relies on certain assumptions: \n",
    "to achieve human-level performance\n",
    "it may be useful to identify *inductive biases* \n",
    "that reflect how humans think about the world.\n",
    "Such inductive biases show preferences \n",
    "for solutions with certain properties.\n",
    "For example,\n",
    "a deep MLP has an inductive bias\n",
    "towards building up a complicated function by the composition of simpler functions.\n",
    "\n",
    "With machine learning models encoding inductive biases,\n",
    "our approach to training them\n",
    "typically consists of two phases: (i) fit the training data;\n",
    "and (ii) estimate the *generalization error*\n",
    "(the true error on the underlying population)\n",
    "by evaluating the model on holdout data.\n",
    "The difference between our fit on the training data\n",
    "and our fit on the test data is called the *generalization gap* and when this is large,\n",
    "we say that our models *overfit* to the training data.\n",
    "In extreme cases of overfitting,\n",
    "we might exactly fit the training data,\n",
    "even when the test error remains significant.\n",
    "And in the classical view,\n",
    "the interpretation is that our models are too complex,\n",
    "requiring that we either shrink the number of features,\n",
    "the number of nonzero parameters learned,\n",
    "or the size of the parameters as quantified.\n",
    "Recall the plot of model complexity compared with loss\n",
    "(:numref:`fig_capacity_vs_error`)\n",
    "from :numref:`sec_generalization_basics`.\n",
    "\n",
    "\n",
    "However deep learning complicates this picture in counterintuitive ways.\n",
    "First, for classification problems,\n",
    "our models are typically expressive enough\n",
    "to perfectly fit every training example,\n",
    "even in datasets consisting of millions\n",
    ":cite:`zhang2021understanding`.\n",
    "In the classical picture, we might think\n",
    "that this setting lies on the far right extreme\n",
    "of the model complexity axis,\n",
    "and that any improvements in generalization error\n",
    "must come by way of regularization,\n",
    "either by reducing the complexity of the model class,\n",
    "or by applying a penalty, severely constraining\n",
    "the set of values that our parameters might take.\n",
    "But that is where things start to get weird.\n",
    "\n",
    "Strangely, for many deep learning tasks\n",
    "(e.g., image recognition and text classification)\n",
    "we are typically choosing among model architectures,\n",
    "all of which can achieve arbitrarily low training loss\n",
    "(and zero training error).\n",
    "Because all models under consideration achieve zero training error,\n",
    "*the only avenue for further gains is to reduce overfitting*.\n",
    "Even stranger, it is often the case that\n",
    "despite fitting the training data perfectly,\n",
    "we can actually *reduce the generalization error*\n",
    "further by making the model *even more expressive*,\n",
    "e.g., adding layers, nodes, or training\n",
    "for a larger number of epochs.\n",
    "Stranger yet, the pattern relating the generalization gap\n",
    "to the *complexity* of the model (as captured, for example, in the depth or width of the networks)\n",
    "can be non-monotonic,\n",
    "with greater complexity hurting at first\n",
    "but subsequently helping in a so-called \"double-descent\" pattern\n",
    ":cite:`nakkiran2021deep`.\n",
    "Thus the deep learning practitioner possesses a bag of tricks,\n",
    "some of which seemingly restrict the model in some fashion\n",
    "and others that seemingly make it even more expressive,\n",
    "and all of which, in some sense, are applied to mitigate overfitting.\n",
    "\n",
    "Complicating things even further,\n",
    "while the guarantees provided by classical learning theory\n",
    "can be conservative even for classical models,\n",
    "they appear powerless to explain why it is\n",
    "that deep neural networks generalize in the first place.\n",
    "Because deep neural networks are capable of fitting\n",
    "arbitrary labels even for large datasets,\n",
    "and despite the use of familiar methods such as $\\ell_2$ regularization,\n",
    "traditional complexity-based generalization bounds,\n",
    "e.g., those based on the VC dimension\n",
    "or Rademacher complexity of a hypothesis class\n",
    "cannot explain why neural networks generalize.\n",
    "\n",
    "## Inspiration from Nonparametrics\n",
    "\n",
    "Approaching deep learning for the first time,\n",
    "it is tempting to think of them as parametric models.\n",
    "After all, the models *do* have millions of parameters.\n",
    "When we update the models, we update their parameters.\n",
    "When we save the models, we write their parameters to disk.\n",
    "However, mathematics and computer science are riddled\n",
    "with counterintuitive changes of perspective,\n",
    "and surprising isomorphisms between seemingly different problems.\n",
    "While neural networks clearly *have* parameters,\n",
    "in some ways it can be more fruitful\n",
    "to think of them as behaving like nonparametric models.\n",
    "So what precisely makes a model nonparametric?\n",
    "While the name covers a diverse set of approaches,\n",
    "one common theme is that nonparametric methods\n",
    "tend to have a level of complexity that grows\n",
    "as the amount of available data grows.\n",
    "\n",
    "Perhaps the simplest example of a nonparametric model\n",
    "is the $k$-nearest neighbor algorithm (we will cover more nonparametric models later, for example in :numref:`sec_attention-pooling`).\n",
    "Here, at training time,\n",
    "the learner simply memorizes the dataset.\n",
    "Then, at prediction time,\n",
    "when confronted with a new point $\\mathbf{x}$,\n",
    "the learner looks up the $k$ nearest neighbors\n",
    "(the $k$ points $\\mathbf{x}_i'$ that minimize\n",
    "some distance $d(\\mathbf{x}, \\mathbf{x}_i')$).\n",
    "When $k=1$, this algorithm is called $1$-nearest neighbors,\n",
    "and the algorithm will always achieve a training error of zero.\n",
    "That however, does not mean that the algorithm will not generalize.\n",
    "In fact, it turns out that under some mild conditions,\n",
    "the 1-nearest neighbor algorithm is consistent\n",
    "(eventually converging to the optimal predictor).\n",
    "\n",
    "\n",
    "Note that $1$-nearest neighbor requires that we specify\n",
    "some distance function $d$, or equivalently,\n",
    "that we specify some vector-valued basis function $\\phi(\\mathbf{x})$\n",
    "for featurizing our data.\n",
    "For any choice of the distance metric,\n",
    "we will achieve zero training error\n",
    "and eventually reach an optimal predictor,\n",
    "but different distance metrics $d$\n",
    "encode different inductive biases\n",
    "and with a finite amount of available data\n",
    "will yield different predictors.\n",
    "Different choices of the distance metric $d$\n",
    "represent different assumptions about the underlying patterns\n",
    "and the performance of the different predictors\n",
    "will depend on how compatible the assumptions\n",
    "are with the observed data.\n",
    "\n",
    "In a sense, because neural networks are over-parametrized,\n",
    "possessing many more parameters than are needed to fit the training data,\n",
    "they tend to *interpolate* the training data (fitting it perfectly)\n",
    "and thus behave, in some ways, more like nonparametric models.\n",
    "More recent theoretical research has established\n",
    "deep connection between large neural networks\n",
    "and nonparametric methods, notably kernel methods.\n",
    "In particular, :citet:`Jacot.Grabriel.Hongler.2018`\n",
    "demonstrated that in the limit, as multilayer perceptrons\n",
    "with randomly initialized weights grow infinitely wide,\n",
    "they become equivalent to (nonparametric) kernel methods\n",
    "for a specific choice of the kernel function\n",
    "(essentially, a distance function),\n",
    "which they call the neural tangent kernel.\n",
    "While current neural tangent kernel models may not fully explain\n",
    "the behavior of modern deep networks,\n",
    "their success as an analytical tool\n",
    "underscores the usefulness of nonparametric modeling\n",
    "for understanding the behavior of over-parametrized deep networks.\n",
    "\n",
    "\n",
    "## Early Stopping\n",
    "\n",
    "While deep neural networks are capable of fitting arbitrary labels,\n",
    "even when labels are assigned incorrectly or randomly\n",
    ":cite:`zhang2021understanding`,\n",
    "this capability only emerges over many iterations of training.\n",
    "A new line of work :cite:`Rolnick.Veit.Belongie.Shavit.2017`\n",
    "has revealed that in the setting of label noise,\n",
    "neural networks tend to fit cleanly labeled data first\n",
    "and only subsequently to interpolate the mislabeled data.\n",
    "Moreover, it has been established that this phenomenon\n",
    "translates directly into a guarantee on generalization:\n",
    "whenever a model has fitted the cleanly labeled data\n",
    "but not randomly labeled examples included in the training set,\n",
    "it has in fact generalized :cite:`Garg.Balakrishnan.Kolter.Lipton.2021`.\n",
    "\n",
    "Together these findings help to motivate *early stopping*,\n",
    "a classic technique for regularizing deep neural networks.\n",
    "Here, rather than directly constraining the values of the weights,\n",
    "one constrains the number of epochs of training.\n",
    "The most common way to determine the stopping criterion\n",
    "is to monitor validation error throughout training\n",
    "(typically by checking once after each epoch)\n",
    "and to cut off training when the validation error\n",
    "has not decreased by more than some small amount $\\epsilon$\n",
    "for some number of epochs.\n",
    "This is sometimes called a *patience criterion*.\n",
    "As well as the potential to lead to better generalization\n",
    "in the setting of noisy labels,\n",
    "another benefit of early stopping is the time saved.\n",
    "Once the patience criterion is met, one can terminate training.\n",
    "For large models that might require days of training\n",
    "simultaneously across eight or more GPUs,\n",
    "well-tuned early stopping can save researchers days of time\n",
    "and can save their employers many thousands of dollars.\n",
    "\n",
    "Notably, when there is no label noise and datasets are *realizable*\n",
    "(the classes are truly separable, e.g., distinguishing cats from dogs),\n",
    "early stopping tends not to lead to significant improvements in generalization.\n",
    "On the other hand, when there is label noise,\n",
    "or intrinsic variability in the label\n",
    "(e.g., predicting mortality among patients),\n",
    "early stopping is crucial.\n",
    "Training models until they interpolate noisy data is typically a bad idea.\n",
    "\n",
    "\n",
    "## Classical Regularization Methods for Deep Networks\n",
    "\n",
    "In :numref:`chap_regression`, we described\n",
    "several  classical regularization techniques\n",
    "for constraining the complexity of our models.\n",
    "In particular, :numref:`sec_weight_decay`\n",
    "introduced a method called weight decay,\n",
    "which consists of adding a regularization term to the loss function\n",
    "in order to penalize large values of the weights.\n",
    "Depending on which weight norm is penalized\n",
    "this technique is known either as ridge regularization (for $\\ell_2$ penalty)\n",
    "or lasso regularization (for an $\\ell_1$ penalty).\n",
    "In the classical analysis of these regularizers,\n",
    "they are considered as sufficiently restrictive on the values\n",
    "that the weights can take to prevent the model from fitting arbitrary labels.\n",
    "\n",
    "In deep learning implementations,\n",
    "weight decay remains a popular tool.\n",
    "However, researchers have noted\n",
    "that typical strengths of $\\ell_2$ regularization\n",
    "are insufficient to prevent the networks\n",
    "from interpolating the data :cite:`zhang2021understanding` and thus the benefits if interpreted\n",
    "as regularization might only make sense\n",
    "in combination with the early stopping criterion.\n",
    "Absent early stopping, it is possible\n",
    "that just like the number of layers\n",
    "or number of nodes (in deep learning)\n",
    "or the distance metric (in 1-nearest neighbor),\n",
    "these methods may lead to better generalization\n",
    "not because they meaningfully constrain\n",
    "the power of the neural network\n",
    "but rather because they somehow encode inductive biases\n",
    "that are better compatible with the patterns\n",
    "found in datasets of interests.\n",
    "Thus, classical regularizers remain popular\n",
    "in deep learning implementations,\n",
    "even if the theoretical rationale\n",
    "for their efficacy may be radically different.\n",
    "\n",
    "Notably, deep learning researchers have also built\n",
    "on techniques first popularized\n",
    "in classical regularization contexts,\n",
    "such as adding noise to model inputs.\n",
    "In the next section we will introduce\n",
    "the famous dropout technique\n",
    "(invented by :citet:`Srivastava.Hinton.Krizhevsky.ea.2014`),\n",
    "which has become a mainstay of deep learning,\n",
    "even as the theoretical basis for its efficacy\n",
    "remains similarly mysterious.\n",
    "\n",
    "\n",
    "## Summary\n",
    "\n",
    "Unlike classical linear models,\n",
    "which tend to have fewer parameters than examples,\n",
    "deep networks tend to be over-parametrized,\n",
    "and for most tasks are capable\n",
    "of perfectly fitting the training set.\n",
    "This *interpolation regime* challenges\n",
    "many hard fast-held intuitions.\n",
    "Functionally, neural networks look like parametric models.\n",
    "But thinking of them as nonparametric models\n",
    "can sometimes be a more reliable source of intuition.\n",
    "Because it is often the case that all deep networks under consideration\n",
    "are capable of fitting all of the training labels,\n",
    "nearly all gains must come by mitigating overfitting\n",
    "(closing the *generalization gap*).\n",
    "Paradoxically, the interventions\n",
    "that reduce the generalization gap\n",
    "sometimes appear to increase model complexity\n",
    "and at other times appear to decrease complexity.\n",
    "However, these methods seldom decrease complexity\n",
    "sufficiently for classical theory\n",
    "to explain the generalization of deep networks,\n",
    "and *why certain choices lead to improved generalization*\n",
    "remains for the most part a massive open question\n",
    "despite the concerted efforts of many brilliant researchers.\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. In what sense do traditional complexity-based measures fail to account for generalization of deep neural networks?\n",
    "1. Why might *early stopping* be considered a regularization technique?\n",
    "1. How do researchers typically determine the stopping criterion?\n",
    "1. What important factor seems to differentiate cases when early stopping leads to big improvements in generalization?\n",
    "1. Beyond generalization, describe another benefit of early stopping.\n",
    "\n",
    "[Discussions](https://discuss.d2l.ai/t/7473)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  },
  "required_libs": []
 },
 "nbformat": 4,
 "nbformat_minor": 5
}